# -*- coding: utf-8 -*-
"""
@Time : 2024/2/23 9:22 PM
@Author: imamhusan
@Des: 分类模块
"""
from fastapi import APIRouter, Request, Depends, Security
from schemes.type import CreateType, UpdateType
from models.type import Type
from core.Response import success, fail, res_antd
from core.Auth import verify_token


router = APIRouter(prefix='/type', dependencies=[Security(verify_token)])


@router.post('', description='添加分类')
async def add_type(req: Request, post: CreateType):
    try:
        new_type = await Type.create(**post.dict())
        if new_type:
            return success(data=new_type, msg='创建成功')
        return fail(msg='创建失败')
    except Exception as e:
        return str(e)


@router.delete('/{id}', description='删除分类')
async def del_type(id: int):
    try:
        # del_ok = await Type.filter(pk=id).delete()
        del_ok = await Type.filter(pk=id).update(state=-1)
        if del_ok:
            return success(data=del_ok, msg='删除成功')
        return fail(msg='删除失败')
    except Exception as e:
        return str(e)


@router.put('', description='修改分类')
async def update_type(post: UpdateType):
    try:
        data = post.dict()
        data.pop('id')
        update_ok = await Type.filter(pk=post.id).update(**data)
        if update_ok:
            return success(data=update_ok, msg='修改成功')
        return fail(msg='修改失败')
    except Exception as e:
        return str(e)


@router.get('', description='获取分类列表')
async def get_type(req: Request, pageSize: int = 7, current: int = 1):
    try:
        lan = req.headers.get('lan', 'uy')
        device = req.headers.get('device', 'mp')

        if device != 'web':
            type_list = await Type.filter(state=1).values('id', 'icon', title=f'title_{lan}')
            return success(data=type_list, msg='获取分类列表')
        else:
            offset = pageSize * (current - 1)
            query = Type.filter(state__not=-1)
            total = await query.count()
            type_list = await query.offset(offset).limit(pageSize).values('id', 'icon', 'state', 'create_time', title=f'title_{lan}')
            return res_antd(data=type_list, total=total)

    except Exception as e:
        return str(e)


@router.get('/{id}', description='获取分类信息')
async def type_info(id : int):
    try:
        type_info = await Type.get_or_none(pk=id)
        if type_info:
            return success(data=type_info, msg='分类信息')
        return fail(msg='获取失败失败')
    except Exception as e:
        return str(e)
